package day07;

/*
 * Author: JacksonCoder
 * FileName: LambdaDemo
 * Version: 1.0.0
 * Date: 2025/4/14
 */


import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

interface MyInterface{
    void sound();
    default void speak(){
        System.out.println("Hello from interface!");
    }
}

class DemoClass implements MyInterface{

    @Override
    public void sound() {
        System.out.println("This is DemoClass of sound method!");
    }
}

public class LambdaDemo {

    public static void main(String[] args) {
        //排序字符串列表
        List<String> list = Arrays.asList("java","python","Go");
        list.sort((a,b) -> a.compareTo(b));
        System.out.println(list);  //[Go, java, python]

        // 对集合数据进行高效处理
        List<String> list1 = Arrays.asList("java","go","python","C","C++");
        List<String> result = list1.stream()
                .filter(s -> s.length() > 3)
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println(result); // [JAVA, PYTHON]

        // Optional (避免NullPointerException)
//        Optional<String> name = Optional.ofNullable(getName());

        // 函数式接口
        Function<String,Integer> stringLength = str -> str.length();
        System.out.println(stringLength.apply("Nexora"));  // 6

        //Predicate
        Predicate<String> isLong = str -> str.length() > 3;
        System.out.println(isLong.test("go")); // false

        // Consumer
        Consumer<String> printer = msg -> System.out.println("Message: " + msg);
        printer.accept("Hello World!");

        // 方法引用（更简洁的Lambda）
        list.forEach(System.out::println); // 等同于 list.forEach(s -> System.out.println(s))
        /**
         * Class::staticMethod
         * object::instanceMethod
         * Class::new（构造方法引用）
         */

        //  接口默认方法（default method）    可以进行子类覆盖
        DemoClass dc = new DemoClass();
        dc.sound();
        dc.speak();
    }

}
